import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'costTime'
})
export class CostTimePipe implements PipeTransform {
  transform(value: any): string {
    if (value instanceof Date) {
      const now: Date = new Date();
      return this.convert(now.getTime() - value.getTime());
    }

    if (!Number.isNaN(value)) {
      return this.convert(value);
    }

    return '';
  }

  convert(value: number): string {
    if (value < 0) {
      value = value * -1;
    }

    const millisecond = Math.floor(value % 1000);
    const seconds = Math.floor((value / 1000) % 60);
    const minutes = Math.floor((value / (1000 * 60)) % 60);
    const hours = Math.floor((value / (1000 * 60 * 60)) % 24);
    const days = Math.floor(value / (1000 * 60 * 60 * 24));

    let rslt = '';
    if (days > 0) {
      rslt = `${days}天`;
    }

    if (hours > 0) {
      rslt = `${rslt}${hours}时`;
    }
    if (minutes > 0) {
      rslt = `${rslt}${minutes}分`;
    }
    if (seconds > 0) {
      rslt = `${rslt}${seconds}秒`;
    }
    if (millisecond > 0) {
      rslt = `${rslt}${millisecond}毫秒`;
    }

    return rslt;
  }
}
